﻿using Cysharp.Threading.Tasks;
using UnityEngine;
using YooAsset;

namespace ResourceFrame
{
    public class YooAssetHelper : Singleton<YooAssetHelper>
    {
        public ResourcePackage Package {get; private set; }

        protected async override void OnInit()
        {
            // 初始化资源系统
            YooAssets.Initialize();
            Package = YooAssets.CreatePackage("DefaultPackage");
            YooAssets.SetDefaultPackage(Package);
            PackageInvokeBuildResult buildResult = EditorSimulateModeHelper.SimulateBuild("DefaultPackage");    
            string packageRoot = buildResult.PackageRootDirectory;
            FileSystemParameters fileSystemParams = FileSystemParameters.CreateDefaultEditorFileSystemParameters(packageRoot);
            //编辑器模式运行
            EditorSimulateModeParameters createParameters = new EditorSimulateModeParameters();
            createParameters.EditorFileSystemParameters = fileSystemParams;
            InitializationOperation initOperation = Package.InitializeAsync(createParameters);
            await initOperation;
            if(initOperation.Status == EOperationStatus.Succeed)
                Debug.Log("资源包初始化成功！");
            else 
                Debug.LogError($"资源包初始化失败：{initOperation.Error}");
            RequestPackageVersionOperation request = Package.RequestPackageVersionAsync();
            await request;
            if (request.Status == EOperationStatus.Succeed)
                Debug.Log($"---RequestPackageVersionAsync:成功");
            else
                Debug.Log($"---RequestPackageVersionAsync:{request.Error}");
            string packageVersion = request.PackageVersion;
            Debug.Log($"---packageVersion:{packageVersion}");
            UpdatePackageManifestOperation updatePackage = Package.UpdatePackageManifestAsync(packageVersion);
            await updatePackage;
            if (updatePackage.Status != EOperationStatus.Succeed)
                Debug.Log($"---TryDownload updatePackage: {updatePackage.Error}");
        }
    }
}